var _Storage = require('utils/storage.js');
var Record = require('config/record.js');
var MAX_RECORD = 20;

// ==========================
// History
// ==========================
function History() {
    this.mStorage = _Storage.internal('history.json', []);
    this.mRecords = [];
}
History.prototype.load = function () {
    var obj = this.mStorage.load();
    var records = [];
    for (var i = 0; i < obj.length; i++) {
        records.push(new Record().load(obj[i]));
    }

    // form high to low
    this.mRecords = records;
    this.__regular();
};
History.prototype.__regular = function () {
    Record.sort(this.mRecords);
    if (this.mRecords.length > MAX_RECORD) {
        this.mRecords.splice(MAX_RECORD);
    }
};
History.prototype.save = function () {
    var obj = [];
    for (var i = 0; i < this.mRecords.length; i++) {
        obj.push(this.mRecords[i].save({}));
    }
    this.mStorage.save(obj);
};
History.prototype.isContains = function (record) {
    for (var i = 0; i < this.mRecords.length; i++) {
        if (this.mRecords[i] === record) {
            return i;
        }
    }
    return -1;
};
History.prototype.createRecord = function (name, cells) {
    return new Record().init(name, cells);
};
/**
 * @param record
 * @returns {Array} return a temp array
 */
History.prototype.addRecord = function (record) {
    this.mRecords.push(record);
    this.__regular();

    var index = this.isContains(record);
    if (index != -1) {
        this.save();
    } else {
        if (this.mRecords[this.mRecords.length - 1].getScore() == record.getScore()) {
            index = this.mRecords.length - 1;
            this.mRecords.pop();
            this.mRecords.push(record);
            this.save();
        }
    }

    var result = [Record.latestRecord(record)].concat(this.mRecords);
    if (index != -1) {
        result.splice(index + 1, 1);
    }
    return result;
};
History.prototype.getRecords = function () {
    return this.mRecords;
};

// single instalce
module.exports = new History();